#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include<unistd.h>

int main(){
    //create socket
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd <0){
        perror("Error");
        exit(-1);
    }

    //define local port
    short local_port = 8081;


    //create structure to store local port and address
    struct sockaddr_in sockaddr_in_local;
    bzero(&sockaddr_in_local, sizeof(sockaddr_in_local));

    sockaddr_in_local.sin_family = AF_INET;
    sockaddr_in_local.sin_port = htons(local_port);
    //local address
    sockaddr_in_local.sin_addr.s_addr = htonl(INADDR_ANY);

    int error_log = bind(sockfd, (struct sockaddr *)&sockaddr_in_local, sizeof(sockaddr_in_local));
    if(error_log != 0){
        perror("error");
        close(sockfd);
        exit(-1);
    } else{
        printf("create socket successfully");
    }

    //receive data
    struct sockaddr_in sockaddr_in_remote;
    bzero(&sockaddr_in_remote, sizeof(sockaddr_in_remote));

    char receive_buf[512] = "";

    int sockaddr_in_remote_len = sizeof(sockaddr_in_remote);

    int recv_nums = recvfrom(sockfd, receive_buf, sizeof(receive_buf), 0, (struct sockaddr *)&sockaddr_in_remote, &sockaddr_in_remote_len);

//    printf("%s\n", receive_buf);

    unsigned char remote_ip[16] = "";
    inet_ntop(AF_INET, &sockaddr_in_remote.sin_addr, remote_ip, 16);
    int remote_port = ntohs(sockaddr_in_remote.sin_port);

    printf("[%s:%d]=>%s\n", remote_ip, remote_port, receive_buf);

}